﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using server.Model;
using server.Tool;
using static FileUtils;

namespace server.DAO
{

    
    public class GameTemplateDao : CommonDao
    {
        private GrounpLifeDao grounpLifeDao = new GrounpLifeDao();
        internal string ResetGameConfig(string grounpId, EditGrounpDao editGrounpDao, KnapsackDao knapsackDao)
        {
            //删除背包
            knapsackDao.GameFinishDelete(int.Parse(grounpId));
            Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId,"grounp");
            editGrounpDao.ResetGameData(grounp);
            grounpLifeDao.ResetData(int.Parse(grounpId));
            return "0";

        }

        /// <summary>
        /// 保存当前模板
        /// </summary>
        /// <param name="grounpId"></param>
        /// <param name="templateName"></param>
        /// <param name="grounpLifeDao"></param>
        /// <returns></returns>
        internal string SaveGameTemplate(string grounpId, string templateName)
        {
            string sql = "select * from game_template where game_id = @game_id and  templateName = @templateName ORDER BY id desc";

            int count = MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@game_id", grounpId),
                new MySqlParameter("@templateName", templateName), });
            if(count>0)
            {
                return "-1";
            }

            Grounp_Life grounp_Life = grounpLifeDao.GetGrounpByPKId(grounpId);
            //info
             sql = "select * from knapsack_info where game_id = @game_id ORDER BY id desc";
            List<Knapsack_Info> knapsack_InfoList  = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql,
                 new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });

            //detail
            sql = "select * from knapsack_detail where game_id = @game_id ORDER BY id desc";
            List<Knapsack_Detail> knapsack_DetailList = MySqlExecuteTools.GetObjectResult<Knapsack_Detail>(sql,
                 new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });


            Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId, "grounp");

            GameTemplateData gameTemplateData = new GameTemplateData()
            {
                infoList = knapsack_InfoList,
                grounp = grounp,
                grounp_Life = grounp_Life,
                detailList = knapsack_DetailList
            };

            //查入数据库
             sql = "insert into game_template(game_id,templateName) " +
                   "values('" + grounpId + "','"  + templateName + "')";
            long newID = MySqlExecuteTools.GetAddID(sql);

            //创建目录
            string path = Environment.CurrentDirectory + "/Data/"+ grounpId;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string jsonPath = path + "/" + newID + ".json";
            string jsonData = Utils.CollectionsConvert.ToJSON(gameTemplateData);

            try
            {
                FileUtils.WriteContent(jsonPath, WriteType.Write, jsonData);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            
            return "0";

        }

        internal string RestoreGameTemplate(string id, KnapsackDao knapsackDao)
        {

            GameTemplateItem gameTemplateItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<GameTemplateItem>(id, "game_template");
            string path = Environment.CurrentDirectory + "/Data/" + gameTemplateItem.game_id + "/" + gameTemplateItem.id + ".json";
            string json = FileUtils.ReadAllContent(path);
            GameTemplateData gameTemplateData = Utils.CollectionsConvert.ToObject<GameTemplateData>(json);
            knapsackDao.DeleteKnapsackByGameId(gameTemplateItem.game_id.ToString());
            //插入背包info数据
            if (gameTemplateData.infoList!=null)
            {
                foreach (Knapsack_Info knapsack_Info in gameTemplateData.infoList)
                {
                   long  newInfoId =  knapsackDao.SaveKnapsackInfoById(knapsack_Info.game_id.ToString(), knapsack_Info.knapsack_id.ToString(),
                        knapsack_Info.startTime.ToString(), knapsack_Info.endTime.ToString(), knapsack_Info.count.ToString(), knapsack_Info.addCountValue.ToString());
                    if(gameTemplateData.detailList != null)
                    {
                        List<Knapsack_Detail> tempList = gameTemplateData.detailList.Where((p) => p.knapsack_info_id == knapsack_Info.id).ToList<Knapsack_Detail>();

                        foreach(Knapsack_Detail item in tempList)
                        {
                            item.knapsack_info_id = (int)newInfoId;
                        }

                        knapsackDao.SaveKnapsackDetail(tempList,false);
                    }


                }
            }
            //插入背包详细数据
            //if(gameTemplateData.detailList!=null)
            //{
            //    foreach (Knapsack_Detail knapsack_Detail in gameTemplateData.detailList)
            //    {
                   
            //    }
            //}

            //更新group

            string sql = "update grounp set  playerTime = '" + gameTemplateData.grounp.playerTime + "', fireTime = '" + gameTemplateData.grounp.fireTime +
              "', fenceLon = '" + gameTemplateData.grounp.fenceLon + "', fenceLat = '" + gameTemplateData.grounp.fenceLat +
              "', fenceRadius = '" + gameTemplateData.grounp.fenceRadius + "', fenceTotalRadius = '" + gameTemplateData.grounp.fenceTotalRadius +
             "', remainTime = '" + gameTemplateData.grounp.remainTime + "' where id = @grounpId";
            MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", gameTemplateData.grounp.id) });

            //更新grounp_life
            grounpLifeDao.UpdateLifeByGrounp(gameTemplateData.grounp_Life.grounp_id.ToString(), gameTemplateData.grounp_Life.lifeValue.ToString(),
                gameTemplateData.grounp_Life.bulletCount.ToString(), gameTemplateData.grounp_Life.hitReduceLifeValue.ToString());

            return "0";
        }

        internal string DelGameTemplate(string id)
        {

            GameTemplateItem item = MySqlExtendTools.GetEntityObjectByPrimaryKey<GameTemplateItem>(id, "game_template");
            if(item!=null)
            {
                string path = Environment.CurrentDirectory + "/Data/" + item.game_id + "/" + item.id + ".json";

                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }

                MySqlExtendTools.DeleteByPrimaryKey(int.Parse(id), "game_template");
            }
            else

            {
                return "-1";
            }
           
            return "0";
        }

        internal string CheckGameTemplate(string grounpId)
        {
           
            Grounp_Life grounp_Life =  grounpLifeDao.GetGrounpByPKId(grounpId);
            if(grounp_Life.bulletCount<=0 || grounp_Life.hitReduceLifeValue<=0 || grounp_Life.lifeValue<=0)
            {
                return "-3";
            }

            //knapsack_info
            string sql = "select * from knapsack_info where game_id = @game_id ORDER BY id desc";
            int count = MySqlExecuteTools.GetCountResult(sql,
                 new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });

            if(count==0)
            {

                return "-2";
            }

            sql = "select * from knapsack_detail where game_id = @game_id ORDER BY id desc";
             count = MySqlExecuteTools.GetCountResult(sql,
                 new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });

            if (count == 0)
            {

                return "-3";
            }

            Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId, "grounp");
            if(grounp!=null && (grounp.playerTime<=0) || grounp.fenceLon<=0)
            {
                return "-1";
            }

            return "0";
        }

        internal string CopyGameTemplate(string id)
        {

            GameTemplateItem item = MySqlExtendTools.GetEntityObjectByPrimaryKey<GameTemplateItem>(id, "game_template");
            SaveGameTemplate(item.game_id.ToString(), item.templateName);
            return "0";
        }

        internal string GetGameTemplateList(string grounpId)
        {
            string sql = "select * from game_template where game_id = @game_id ORDER BY id desc";
            List<GameTemplateItem> list = MySqlExecuteTools.GetObjectResult<GameTemplateItem>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });
            if(list.Count>0)
            {
                return Utils.CollectionsConvert.ToJSON(list);
            }
            else
            {
                return "-1";
            }
            

        }

        /// <summary>
        /// 更新模板名称
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tname"></param>
        /// <returns></returns>
        internal string UpdateGameTemplateName(string id, string tname)
        {
            string sql = "update game_template set  templateName = '" + tname + "' where id = @id";
            MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@id", id) });
            return "0";
        }
    }
}
